// @algorithm @lc id=105 lang=cpp 
// @title construct-binary-tree-from-preorder-and-inorder-traversal


#define print(...)
// @test([3,9,20,15,7],[9,3,15,20,7])=[3,9,20,null,null,15,7]
// @test([-1],[-1])=[-1]
// 前序遍历：[ 根节点, [左子树的前序遍历结果], [右子树的前序遍历结果] ]
// 中序遍历：[ [左子树的中序遍历结果], 根节点, [右子树的中序遍历结果] ]
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        unordered_map<int,int> inPos; // val 在 inorder 中的index，方便找root
        int n = inorder.size();
        for(int i=0; i<n; i++)
            inPos[inorder[i]] = i;
        function<TreeNode*(int,int,int,int)> build =
            [&](int pFront, int pBack, int iFront, int iBack)->TreeNode*{
            if(pFront > pBack || iFront > iBack) return NULL;
            auto root = new TreeNode(preorder[pFront]);
            int iRoot = inPos[root->val];
            print(iRoot, ": [",pFront,",",pBack,"] [",iFront,",",iBack,"]\n")
            int leftSize = iRoot - iFront, rightSize = iBack - iRoot;
            root->left = build(pFront+1, pFront+leftSize, iFront, iRoot-1);
            root->right= build(pFront+leftSize+1, pBack, iRoot+1, iBack);
            return root;
        };
        return build(0, n-1, 0, n-1);
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */